package com.tnsw.noxnox;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.tnsw.noxnox.R;
import com.tnsw.noxnox.db.DBManager;
import com.tnsw.noxnox.downloader.YoutubeDL;
import com.tnsw.noxnox.lab.LabWebViewFragment;
import com.tnsw.noxnox.streamer.MediaHandler;
import com.tnsw.noxnox.util.JSONParameter;
import com.tnsw.noxnox.util.ServerHelper;
import com.tnsw.noxnox.util.ServerHelperListener;
import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.files.FileUtils;
import com.tnsw.coreutils.text.TextUtils;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener, ViewPager.OnPageChangeListener  {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	private ViewPagerInterceptable mViewPager;
	
	private String tag = "MainActivity";
	private AsyncManager asyncManager;
	private ActionBar actionBar;

	public MainActivity() {
		super();
		this.asyncManager = AsyncManager.getInstance();
		Log.d(tag, "Constructor()");
	}
	
	private void initialize() {
		try {
			GCMRegistrar.checkDevice(this);
			GCMRegistrar.checkManifest(this);
			String registrationId = GCMRegistrar.getRegistrationId(this);
			if (registrationId.equals("")) {
				Log.d(tag, "Not registered yet, going to register");
				GCMRegistrar.register(this, "518191396700");
				registrationId = GCMRegistrar.getRegistrationId(this);
				Log.d(tag, "registrationId=" + registrationId);
			} else {
				Log.d(tag, "Registered already, registrationId=" + registrationId);
			}			
		} catch (Exception e) {
			Log.e(tag, "initialize() - " + e.toString(), e);
		}
		
		try {
			PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			Log.d(tag, "versionCode=" + packageInfo.versionCode);
			Log.d(tag, "versionName=" + packageInfo.versionName);
			ServerHelper.VERSIONCODE = packageInfo.versionCode;
			ServerHelper.VERSIONNAME = packageInfo.versionName;
		} catch (Exception e) {
			Log.e(tag, "Packageinfo - " + e.toString(), e);
		}
		
		boolean b = AsyncManager.isServiceRunning(this, com.tnsw.noxnox.streamer.StreamerService.class.getName());
		if (b == false) {
			Intent intent = new Intent(this, com.tnsw.noxnox.streamer.StreamerService.class);
			this.startService(intent);
		}
		
		b = AsyncManager.isServiceRunning(this, com.tnsw.noxnox.settopbox.STBService.class.getName());
		if (b == false) {
			//Intent intent = new Intent(this, com.tnsw.noxnox.settopbox.STBService.class);
			//this.startService(intent);
		}
		
		b = AsyncManager.isServiceRunning(this, com.tnsw.noxnox.GCMIntentService.class.getName());
		if (b == false) {
			Intent intent = new Intent(this, com.tnsw.noxnox.GCMIntentService.class);
			this.startService(intent);
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(tag, "onCreate(Bundle)");
		setContentView(R.layout.activity_main);
		
		asyncManager.appendNetworkLog("Test from NoxNox");
		this.asyncManager.dumpDeviceInfo(this);
		
		String str = TextUtils.getFinishWhen(86400);
		Log.d(tag, str);
		
		int l[] = MediaHandler.getRanges("bytes=70640865-186257407", 12345);
		Log.d(tag, "l[0]=" + l[0] + ", l[1]=" + l[1]);
		
		this.initialize();

		// Set up the action bar.
		this.actionBar = this.getActionBar();
		this.actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPagerInterceptable) findViewById(R.id.pager);
		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), this, mViewPager);		
		mViewPager.setAdapter(mSectionsPagerAdapter);
		
		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		/*
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
						Log.d(tag, "onPageSelected(position=" + position + ")");
					}
				});
		*/

		mViewPager.setOnPageChangeListener(this);
		
		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			Tab tab = actionBar.newTab();
			tab.setText(mSectionsPagerAdapter.getPageTitle(i));
			tab.setTabListener(this);
			
			actionBar.addTab(tab);
			
			
			//actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
		}
		
		
		mViewPager.setCurrentItem(0);
		
		/*
		Intent intent = new Intent(this, com.tnsw.noxnox.SignupActivity.class);
		Log.d(tag, "created intent");
		this.startActivity(intent);
		*/
		
		/*
		Intent intent = new Intent(this, com.tnsw.noxnox.CatalogActivity.class);
		this.startActivity(intent);
		*/
	}
	
	@Override
	protected void onSaveInstanceState (Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(tag, "onSaveInstanceState()");
		
	}	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		this.getMenuInflater().inflate(R.menu.activity_main, menu);
		SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		
		case R.id.menu_signin:
			/*
			Intent intentfb = new Intent(this, com.tnsw.noxnox.facebook.FacebookLoginActivity.class);
			this.startActivity(intentfb);
			*/
			
			break;
		
		case android.R.id.home:
			Log.d(tag, "Hit home");
			CatalogFragment ff = (CatalogFragment) this.mSectionsPagerAdapter.fgCatalog;
			ff.returnHome();
			break;
		
		case R.id.menu_settings:

			Intent intent = new Intent(this, com.tnsw.noxnox.facebook.FacebookLoginActivity.class);
			this.startActivity(intent);
			break;
		
		case R.id.menu_uploaddb:
			DBManager dbm = DBManager.getInstance(this);
			try {
				byte[] b = FileUtils.readFile(dbm.getFullDatabasePath());
				String base64 = Base64.encodeToString(b, Base64.DEFAULT);
				this.asyncManager.appendBase64(base64, "noxnoxdb.s3db");	
				Toast.makeText(this, "Upload done", Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				Log.e(tag, e.toString(), e);
			}
			break;
			
		case R.id.menu_setting1:
			Intent i2 = new Intent(this, com.tnsw.noxnox.signin.SigninActivity.class);
			this.startActivity(i2);
			break;
			
		case R.id.menu_jwplayer:
			ArrayList<JSONParameter> a = new ArrayList<JSONParameter>();
			a.add(new JSONParameter("uniqueid", "xxyyzz"));
			a.add(new JSONParameter("os_type", 1));
			a.add(new JSONParameter("os_version", android.os.Build.VERSION.RELEASE));
			JSONArray jArray = new JSONArray();
			jArray.put("1");
			jArray.put("2");
			//a.add(new JSONParameter("array1", jArray));
			
			ServerHelper sh = new ServerHelper(this, "register", a, new ServerHelperListener() {
				
				@Override
				public void onComplete(ServerHelper sender, Long result, String jsonStr, JSONObject jsonObj, String command, String tranid) {
					Log.d("helper", "onComplete, result=" + String.valueOf(result) + ", command=" + command + ", tranid=" + tranid);
					try {
						JSONObject arguments = (JSONObject) jsonObj.get("arguments");
						Log.d("helper", "primarykey=" + arguments.getLong("primarykey"));	
					} catch (Exception e) {
						Log.e("helper", "onComplete - " + e.toString(), e);
					}
					
					
				}
			});
			
			sh.run();
			
			break;
		}
		
		return(true);
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

		Log.d(tag, "onTabSelected(tab.getPosition=" + tab.getPosition() + ")");
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		Log.d(tag, "onTabUeselected(tab.getPosition=" + tab.getPosition() + ")");
		if (tab.getPosition() == 0) {
			CatalogFragment f = (CatalogFragment) this.mSectionsPagerAdapter.fgCatalog;
			f.detachFromOutsite();
		}
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		Log.d(tag, "onTabReselected(tab.getPosition=" + tab.getPosition() + ")");
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		private Context context;
		private ViewPagerInterceptable mParentViewPager;
		
		public Fragment fgCatalog;
		public Fragment fgYoutube;
		public Fragment fgLabWebView;
		
		public SectionsPagerAdapter(FragmentManager fm, Context context, ViewPagerInterceptable parentViewPager) {
			this(fm);
			this.context = context;
			this.mParentViewPager = parentViewPager;
			
			this.fgCatalog = CatalogFragment.newInstance(context, this);
			this.fgYoutube = YoutubeFragment.newInstance(context, this);
			this.fgLabWebView = LabWebViewFragment.newInstance(context, this);
			
			DBManager dbm = DBManager.getInstance(context);
			dbm.DBDispatcher.register((CatalogFragment) this.fgCatalog);
			
		}
		
		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			
			/*
			Fragment fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			return fragment;
			*/
			
			Fragment f = new Fragment();
			switch (position) {
			case 0:
				//f = WhatsHot.newInstance(this.context);
				//f = CatalogFragment.newInstance(this.context);
				f = this.fgCatalog;
				CatalogFragment ff = (CatalogFragment) this.fgCatalog;
				ff.returnHome();
				break;
			
				
			case 1:
				//f = MyScrollView.newInstance(this.context, this.mParentViewPager);
				//f = YoutubeFragment.newInstance(this.context);
				f = this.fgYoutube;
				break;
				
			case 2:
				f = this.fgLabWebView;
				break;
			}
			
			return(f);
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				//return getString(R.string.title_section1).toUpperCase();
				return("Catalog");
			case 1:
				//return getString(R.string.title_section2).toUpperCase();
				return("Test DL");
			case 2:
				//return getString(R.string.title_section3).toUpperCase();
				return("LabWebView");
			}
			return null;
		}
	}
	

	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		
	}

	@Override
	public void onPageSelected(int arg0) {
		Log.d(tag, "onPageSelected(arg0=" + arg0 + ")");
		this.actionBar.setSelectedNavigationItem(arg0);
		
		if (arg0 == 0) {
			CatalogFragment f = (CatalogFragment) this.mSectionsPagerAdapter.getItem(arg0);
			f.doRefresh();
		} else if (arg0 == 1) {
			YoutubeFragment f = (YoutubeFragment) this.mSectionsPagerAdapter.getItem(arg0);
			
		}
		
	}

	
}
